<template>
    <div id="content">
        <div id="header-content">
            <el-form label-width="80px">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="计算日期:">
                            <el-date-picker
                                v-model="calcDate"
                                type="daterange"
                                range-separator="-"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                @change="handleDateRange"
                                value-format="yyyyMMdd"
                                size="small"
                                style="width: 100%"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="条目编号:">
                            <el-input
                                placeholder="支持','分割"
                                v-model="entryCodeList"
                                size="mini"
                                style="width: 60%"
                                @change="handleEntryCodeList"
                            ></el-input>
                            <el-checkbox
                                v-model="queryParam.precision"
                                size="mini"
                                style="width: 40%; border: 1px solid #ccc; border-left: none; height: 26px; line-height: 22px"
                                >准确搜索</el-checkbox
                            >
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="风险说明:">
                            <el-input v-model="queryParam.entryName" placeholder="" size="mini" style="width: 100%"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="触警类型:">
                            <el-select v-model="queryParam.triggerType" clearable style="width: 100%" size="mini">
                                <el-option
                                    v-for="item in thresholdType"
                                    :key="item.dictKey"
                                    :value="item.dictKey"
                                    :label="item.dictKey + ' ' + item.dictKeyName"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="产品代码:" :class="{ isInput: queryParam.fundCodes.length > 0 }">
                            <el-select
                                v-model="queryParam.fundCodes"
                                size="mini"
                                style="width: 100%"
                                placeholder=""
                                filterable
                                multiple
                                collapse-tags
                            >
                                <el-option
                                    v-for="item in computedFunds"
                                    :key="item.fundCode"
                                    :value="item.fundCode"
                                    :label="item.showCode + ' ' + item.fundNameSt"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="证券代码:" :class="{ isInput: queryParam.stockCodes.length > 0 }">
                            <el-select
                                style="width: 100%"
                                v-model="queryParam.stockCodes"
                                clearable
                                filterable
                                multiple
                                collapse-tags
                                remote
                                :remote-method="getBondCodeList"
                                :loading="selectLoading"
                                size="mini"
                            >
                                <el-option
                                    v-for="item in bondCodeSelectData"
                                    :key="item.dictKey"
                                    :label="item.dictKey + ' ' + item.dictKeyName"
                                    :value="item.dictKey"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="备注信息:">
                            <el-input v-model="queryParam.remark" size="mini" placeholder="" style="width: 100%"> </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="处理人:" :class="{ isInput: queryParam.handeUsers.length > 0 }">
                            <el-select v-model="queryParam.handeUsers" clearable filterable multiple collapse-tags size="mini" style="width: 100%">
                                <el-option
                                    v-for="item in computedOrderUsers"
                                    :key="item.dictKey"
                                    :value="item.dictCode"
                                    :label="item.dictKey + ' ' + item.dictKeyName"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-button type="primary" size="mini" @click="handleButtonClick('refresh')"> 刷新</el-button>
                    <el-button type="primary" size="mini" @click="handleButtonClick('search')"> 查询</el-button>
                    <el-button type="primary" size="mini" @click="handleButtonClick('loadout')"> 导出</el-button>
                </el-row>
            </el-form>
        </div>
        <div id="main-content">
            <el-table
                auto-resize
                resizable
                stripe
                :data="dataSource"
                :key="tableKey + 'tableKey'"
                border
                v-loading="tableLoading"
                element-loading-text="加载中"
                size="mini"
                height="calc(100vh - 275px)"
                ref="table"
                :row-key="resultId"
                @select="handleSelection"
                @selection-change="handleSelectionChange"
            >
                <!-- <el-table-column width="55" type="selection"> </el-table-column> -->
                <TableSelection
                    row-key="resultId"
                    :current-page-table-list="dataSource"
                    :selected="tableSelectedList"
                    :drop-down-list="[{ text: '选择全部页', value: 'all' }]"
                    show-drop-down
                    @dropdown-click="dropdownClick"
                    @getSelected="getSelected"
                />
                <el-table-column prop="calDate" label="计算日期" min-width="110" show-overflow-tooltip align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.calDate != undefined ? dateFormat(scope.row.calDate) : '--' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="entryCode" label="条目编号" min-width="110" show-overflow-tooltip> </el-table-column>
                <el-table-column prop="entryName" label="风险说明" min-width="110" show-overflow-tooltip> </el-table-column>
                <!-- <el-table-column prop="compareType" label="比较方向" min-width="110" show-overflow-tooltip> </el-table-column> -->
                <el-table-column prop="thresholdValue" label="触警阈值" min-width="110" show-overflow-tooltip> </el-table-column>
                <el-table-column prop="fundCode" label="产品代码" min-width="110" show-overflow-tooltip> </el-table-column>
                <!-- <el-table-column prop="fundName" label="产品名称" min-width="110" show-overflow-tooltip> </el-table-column> -->
                <el-table-column prop="thresholdType" label="触警类型" min-width="110" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <StatusTag :code="scope.row.thresholdType"></StatusTag>
                    </template>
                </el-table-column>
                <el-table-column prop="calValue" label="计算结果" min-width="110" show-overflow-tooltip align="right">
                    <template slot-scope="scope">
                        <span>{{
                            WEB_DOCKING === 'CIBFUND' && scope.row.calValue != undefined
                                ? numberFormatXDAY(scope.row.calValue)
                                : scope.row.calValue != undefined
                                ? numberFormat(scope.row.calValue)
                                : '--'
                        }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="stockName" label="证券代码" min-width="110" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-tag size="small" style="" v-if="scope.row.stockInfos != null && scope.row.stockInfos.length > 1" slot="reference">
                            <el-tooltip placement="top">
                                <ul slot="content" style="max-height: 200px; overflow: auto">
                                    <li :key="item.dictKey" v-for="item in scope.row.stockInfos">
                                        {{ item.dictKey + ':' + item.dictKeyName }}
                                    </li>
                                </ul>

                                <span>{{ scope.row.stockInfos.length + '个证券' }}</span>
                            </el-tooltip>
                        </el-tag>
                        <span v-else-if="scope.row.stockInfos != null && scope.row.stockInfos.length == 1">
                            {{ scope.row.stockInfos[0].dictKey + ':' + scope.row.stockInfos[0].dictKeyName }}
                        </span>
                        <span v-else> --</span>
                    </template>
                </el-table-column>
                <el-table-column prop="calLogic" label="计算逻辑" min-width="110" show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{ formatterValue(scope.row.calLogic) }}
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注信息" min-width="110" show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{ formatterValue(scope.row.remark) }}
                    </template>
                </el-table-column>
                <el-table-column prop="handeUsers" label="处理人" min-width="110" show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{ formatterValue(scope.row.handeUsers) }}
                    </template>
                </el-table-column>
            </el-table>
            <risk-pagination :paging="paging" @page-change="handleCurrentChange"></risk-pagination>
        </div>
    </div>
</template>
<script lang="ts">
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { downLoadFile } from '@/utils/request';
import { changeOptions, dateFormat, numberFormat, getConfigItem, numberFormatXDAY } from '@/utils/tools';
import { Component, Vue } from 'vue-property-decorator';
import XEUtils from 'xe-utils';
import StatusTag from '../risk-measure/components/status-tag.vue';
import TableSelection from './components/table-selection.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import moment from 'moment';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'TouchAlarmEntry',
    components: {
        StatusTag,
        TableSelection,
        RiskPagination,
    },
})
export default class TouchAlarmEntry extends Vue {
    numberFormatXDAY = numberFormatXDAY;
    WEB_DOCKING = getConfigItem('WEB_DOCKING');
    numberFormat = numberFormat;
    dateFormat = dateFormat;
    private calcDate: any[] = [moment(new Date()).subtract(1, 'day').format('YYYYMMDD'), moment(new Date()).subtract(1, 'day').format('YYYYMMDD')]; // 计算日期

    private tableLoading: boolean = false; // 表数据加载

    private dataSource: any[] = []; // 表数据

    tableKey: number = -1; // 表格页面渲染

    private thresholdType: any[] = []; // 触警类型

    private funds: any[] = []; // 产品代码

    private selectLoading: boolean = false; // 下拉框加载

    private bondCodeSelectData: any[] = []; // 证券代码下拉框数据

    private entryCodeList: string = ''; // 条目编号
    private queryParam = {
        stockCodes: [],
        fundCodes: [],
        handeUsers: [],
        startCalDate: moment(new Date()).subtract(1, 'day').format('YYYYMMDD'),
        endCalDate: moment(new Date()).subtract(1, 'day').format('YYYYMMDD'),
    }; // 查询条件

    private orderUsers: any[] = [];
    private CompareDirection = {
        '0': '>',
        '1': '<',
        '2': '>=',
        '3': '<=',
        '4': '=',
        '5': '<>',
        '6': ' ',
    };
    private paging: pages = {
        pageSize: 50,
        currentPage: 1,
        total: 0,
    };
    private tableSelectedList: any[] = [];
    private selectedData: any[] = [];
    private selectType: string = '3'; // 1 选择所有页，2 选择当前页 3 多选;
    tableAllSelectedList: any[] = [];

    async mounted() {
        // 产品信息
        this.funds = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);

        this.thresholdType = DictionConstUtil.PojoToList(DictionConstUtil.ThresholdType).filter(item => item.dictKey !== '4');
        // 新增部分，发送Ajax获取  “证券代码”列表
        await this.getBondCodeList('');

        // 处理人
        this.getSelectValue();

        this.getQuery();
    }

    // 产品代码已选项前置
    get computedFunds() {
        let funds = changeOptions(this.queryParam.fundCodes, this.funds, 'fundCode');
        return funds;
    }

    // 处理人已选项前置
    get computedOrderUsers() {
        let orderUsers = changeOptions(this.queryParam.handeUsers, this.orderUsers, 'dictCode');
        return orderUsers;
    }

    // 处理人多选框数据源
    private getSelectValue(): void {
        this.$axios({
            url: 'instruction/user/select',
            method: 'post',
        }).then((res: any) => {
            this.orderUsers = res;
        });
    }

    getQuery(): void {
        this.tableLoading = true;
        this.$axios
            .post('/touchAlarmEntry/history/list', { ...this.queryParam, paging: this.paging })
            .then((res: any) => {
                this.tableLoading = false;
                this.paging.total = res.total;
                res.list.forEach(ele => {
                    ele.thresholdValue = this.CompareDirection[ele.compareType] + ele.thresholdValue;
                    if (ele.fundName) {
                        ele.fundCode = ele.fundCode + '(' + ele.fundName + ')';
                    }
                });
                this.dataSource = res.list;
                this.tableKey++;
            })
            .catch(() => {
                this.tableLoading = false;
            });
    }

    // 获取证券代码下拉框数据
    private getBondCodeList(e: string): void {
        this.selectLoading = true;
        this.$axios
            .post('/dict/stock/select', {
                dictKey: e,
                dictKeyName: e,
            })
            .then((res: any) => {
                this.bondCodeSelectData = res || [];
                this.selectLoading = false;
            })
            .catch(() => {
                this.selectLoading = false;
            });
    }

    handleDateRange(value: any) {
        if (value) {
            this.queryParam['startCalDate'] = value[0];
            this.queryParam['endCalDate'] = value[1];
        } else {
            this.queryParam['startCalDate'] = null;
            this.queryParam['endCalDate'] = null;
        }
    }

    handleEntryCodeList(value: string) {
        this.queryParam['entryCodeList'] = value.split(',');
    }

    // 分页
    private handleCurrentChange(curPage: number): void {
        //    this.paging.currentPage = curPage;
        this.getQuery();
    }

    // 全选方法
    dropdownClick(command) {
        this.tableSelectedList = [];
        this.selectedData = [];
        if (command === 'all') {
            this.selectType = '1';

            // let tableSelectedList = this.tableSelectedList;
            // this.selectedData = this.dataSource;
            // this.dataSource.forEach((item) => {
            //     if (!tableSelectedList.includes(item.resultId)) {
            //         tableSelectedList.push(item.resultId);
            //     }
            // });
        } else if (command === 'current') {
            this.selectType = '2';
        }
    }
    getSelected(val: any) {
        let select = this.dataSource.filter(ele => this.tableSelectedList.includes(ele.resultId));
        this.selectedData = this.selectedData.concat(select);
        let set = new Set(this.selectedData);
        this.selectedData = Array.from(set);
    }

    // 点击
    private handleButtonClick(type: string): void {
        let rowSelection = [];
        if (type == 'refresh') {
            this.paging.currentPage = 1;
            this.getQuery();
        } else if (type == 'search') {
            this.paging.currentPage = 1;
            this.getQuery();
        } else {
            // 导出
            let rows = (this.$refs as any).table.selection;

            let exportData = [];
            exportData = this.selectedData.filter(ele => {
                return this.tableSelectedList.includes(ele.resultId);
            });
            rowSelection = XEUtils.map(exportData, item => {
                return {
                    resultId: item.resultId,
                    calDate: item.calDate,
                };
            });
            downLoadFile({
                url: '/touchAlarmEntry/history/export',
                method: 'post',
                data: { ...this.queryParam, rowSelection: rowSelection },
                loading: true,
                loadingMsg: '正在准备导出，请稍后··· ···',
            });
        }
    }

    // 手动勾选事件
    handleSelection(selection: any, row: any) {
        this.selectType = '3';
    }

    // 勾选数据变化事件
    handleSelectionChange(val: any) {}

    formatterValue(value): void {
        return value === 0 || (value && value != '空' && (value + '').trim()) ? value : '--';
    }
}
</script>
<style lang="scss" scoped>
#content {
    min-width: 1200px;
    padding: 10px 20px;
    #header-content {
        border: 1px solid #ccc;
        padding: 10px;
        margin-bottom: 20px;
        /deep/.el-form-item {
            margin-bottom: 10px;
            .el-form-item__label {
                color: black;
            }
        }

        /deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light {
            display: flex;
            align-items: center;
            width: 74%;
            max-width: fit-content;
            padding: 0px;
            margin: 2px 0 2px 2px;
            .el-select__tags-text {
                display: inline-block;
                font-size: 12px;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }
        /deep/ .el-select {
            .el-tag__close.el-icon-close {
                right: 1px;
            }
        }
        /deep/ .el-range-editor.is-active,
        .el-range-editor.is-active:hover {
            border-color: #409eff;
        }
    }
    #main-content {
        border: 1px solid #ccc;
        padding: 10px;
    }
}
.isInput /deep/ .el-select__input {
    margin-left: 2px;
}
</style>
